/*
 * 官网地站:http://www.mob.com
 * 技术支持QQ: 4006852216
 * 官方微信:ShareSDK   （如果发布新版本的话，我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题，也可以通过微信与我们取得联系，我们将会在24小时内给予回复）
 *
 * Copyright (c) 2013年 mob.com. All rights reserved.
 */

package com.kanshu.ksgb.fastread.doudou.wxapi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent;
import com.kanshu.ksgb.fastread.doudou.module.login.thirdlogin.BindHelper;
import com.kanshu.ksgb.fastread.doudou.module.login.thirdlogin.ThirdService;
import com.kanshu.ksgb.fastread.doudou.module.login.thirdlogin.WxAccessTokenParams;
import com.kanshu.ksgb.fastread.doudou.module.login.thirdlogin.WxRetrofit;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.BindInfo;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * 微信客户端回调activity示例
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    public static final int TYPE_OTHER = 1;
    public static final int TYPE_BIND_WITHDRAW = 2;
    public static int WX_TYPE = TYPE_OTHER;
    IWXAPI mApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApi = WXAPIFactory.createWXAPI(getApplicationContext(), getWxAppID(this), false);
        mApi.handleIntent(getIntent(), this);
        EventBus.getDefault().register(this);
    }

    public static final String getWxAppID(Context context){
        String appId = null;
       // switch (WX_TYPE){
        //    case TYPE_BIND_WITHDRAW:
         //       appId = context.getString(R.string.wx_app_id_withdraw);
          //      break;
           // case TYPE_OTHER:
            //default:
                appId = context.getString(R.string.wx_app_id);
             //       break;
        //}
       return appId;
    }



    public static final String getWxAppSecret(Context context){
        String appSecret = null;
/*        switch (WX_TYPE){
            case TYPE_BIND_WITHDRAW:
                appSecret = context.getString(R.string.wx_app_secret_withdraw);
                break;
            case TYPE_OTHER:
            default:*/
                appSecret = context.getString(R.string.wx_app_secret);
              //  break; }
        return appSecret;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mApi.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        switch (baseResp.getType()) {
            case ConstantsAPI.COMMAND_SENDAUTH://登录回调
                if (BaseResp.ErrCode.ERR_OK == baseResp.errCode) {
                    if (baseResp instanceof SendAuth.Resp) {
                        SendAuth.Resp newResp = (SendAuth.Resp) baseResp;
                        //获取微信传回的code
                        getAccessToken(newResp.code);
                    }
                } else if (BaseResp.ErrCode.ERR_USER_CANCEL == baseResp.errCode) {
                    BindEvent bindEvent = new BindEvent();
                    bindEvent.code = BindEvent.FAILED;
                    EventBus.getDefault().post(bindEvent);
                    finish();
                } else {
                    ToastUtil.showMessage(this, "微信授权失败");
                    finish();
                }
                break;
            case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX://分享回调
                if (BaseResp.ErrCode.ERR_OK == baseResp.errCode) {
                } else if (BaseResp.ErrCode.ERR_USER_CANCEL == baseResp.errCode) {
                } else {
                }
                finish();
                break;
            default:
                break;
        }
    }

    private void getAccessToken(String code) {
        RetrofitHelper helper = RetrofitHelper.getInstance();
        //helper.setRetrofit(WxRetrofit.getInstance());
        WxAccessTokenParams params = new WxAccessTokenParams();
        params.appid = getWxAppID(this);
        params.secret = getWxAppSecret(this);
        params.code = code;
        params.grant_type = "authorization_code";
        Map<String, String> map = JsonUtils.jsonStrToMap(params.toJsonStr());
        helper.createService(WxRetrofit.class, ThirdService.class).getAccessToken(map).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(ResponseBody responseBody) {
                String jsonStr = null;
                try {
                    jsonStr = responseBody.string();
                    if (jsonStr != null) {
                        JSONObject object;
                        try {
                            object = new JSONObject(jsonStr);
                            String open_id = object.getString("openid");
                            String unionid = object.getString("unionid");
                            String access_token = object.getString("access_token");
                            // 获取用户信息
                            getWxUserInfo(access_token, open_id, unionid);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                Log.d("wcy", "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private void getWxUserInfo(final String access_token, final String openid, final String unionid) {
        RetrofitHelper helper = RetrofitHelper.getInstance();
        //helper.setRetrofit(WxRetrofit.getInstance());
        Map<String, String> map = new HashMap<>();
        map.put("access_token", access_token);
        map.put("openid", openid);
        helper.createService(WxRetrofit.class, ThirdService.class).getWxUserInfo(map).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(ResponseBody responseBody) {
                String jsonStr = null;
                try {
                    jsonStr = responseBody.string();
                    if (jsonStr != null) {
                        JSONObject jsonObject;
                        try {
                            jsonObject = new JSONObject(jsonStr);
                            String nickname = jsonObject.optString("nickname");
                            String headimgurl = jsonObject.optString("headimgurl");
                            // 保存用户昵称和头像
                            StorageUtils.setPreference(Xutils.getContext(), Constants.SP_NAME, Constants.NICK_NAME, nickname);
                            StorageUtils.setPreference(Xutils.getContext(), Constants.SP_NAME, Constants.HEADER_IMG, headimgurl);
//                            if(TYPE_BIND_WITHDRAW == WX_TYPE){
//                                Map<String,String> params = JsonUtils.jsonStrToMap(new BaseRequestParams().toJsonStr());
//                                params.put("openid", openid);
//                                params.put("nickname",nickname);
//                                BindHelper.bindWxWitdraw(params);
//                            }else{
//                                BindRequestParams params = new BindRequestParams();
//                                params.openid = openid;
//                                params.unionid = unionid;
//                                params.access_token = access_token;
//                                params.type = Constants.TYPE_LOGIN_BY_WX;
//                                BindHelper.bind(params);
//                            }
                            Map<String,String> params = new HashMap<>();
                            params.put("openid", openid);
                            params.put("nickname",nickname);
                            BindHelper.bindWxWitdraw(params);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void handleBindEvent(BindInfo event) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void handleBindEvent(BindEvent event) {
        finish();
    }
}
